package com.crois.barrier.web.plugin.post;

import com.alibaba.fastjson.JSONObject;
import com.crois.barrier.common.dto.ApiRouteInfo;
import com.crois.barrier.common.dto.StatisticsSend;
import com.crois.barrier.common.enums.PluginEnum;
import com.crois.barrier.common.enums.PluginTypeEnum;
import com.crois.barrier.common.utils.IpUtil;
import com.crois.barrier.plugin.BarrierPluginChain;
import com.crois.barrier.web.cache.CacheManager;
import com.crois.barrier.web.plugin.AbstractBarrierPlugin;
import com.crois.barrier.web.statistics.StatisticsSvc;
import com.crois.barrier.web.support.ServerWebExchangeUtils;
import com.zhimydou.ztools.collection.CollectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Hou Ze Yu
 * @description 统计插件
 * @date 2020/5/7
 */
public class StatisticsPlugin extends AbstractBarrierPlugin {

    private CacheManager cacheManager;

    private StatisticsSvc statisticsSvc;

    Logger LOGGER = LoggerFactory.getLogger(StatisticsPlugin.class);

    public StatisticsPlugin(CacheManager cacheManager,StatisticsSvc statisticsSvc) {
        super(cacheManager);
        this.cacheManager = cacheManager;
        this.statisticsSvc = statisticsSvc;
    }

    @Override
    public PluginTypeEnum pluginType() {
        return PluginTypeEnum.POST;
    }

    @Override
    public String name() {
        return PluginEnum.STATICS.getName();
    }

    @Override
    public int order() {
        return PluginEnum.STATICS.getCode();
    }
    @Override
    public Boolean skip(ServerWebExchange exchange) {
        //
        ApiRouteInfo routeInfo = (ApiRouteInfo) exchange.getAttributes().get(ServerWebExchangeUtils.BARRIER_ROUTE_ATTR);
        if (CollectionUtil.isNotEmpty(routeInfo.getPlugins())){
            return !routeInfo.getPlugins().contains(PluginEnum.STATICS.getName());
        }else {
            return true;
        }
    }

    @Override
    protected Mono<Void> doExecute(ServerWebExchange exchange, BarrierPluginChain chain, ApiRouteInfo routeInfo) {
            // 执行 统计 操作
            LOGGER.info("[开始执行：StatisticsPlugin]");
            String requestPath = String.valueOf(exchange.getAttributes().get(ServerWebExchangeUtils.BARRIER_REQUEST_PATH));
            statisticsSvc.sendStatistics(JSONObject.toJSONString(new StatisticsSend(IpUtil.getIpAddress(exchange.getRequest()),routeInfo.getId(),routeInfo.getApiRouteName(),requestPath,routeInfo.getRequestMethod())));
            LOGGER.info("[执行完成：StatisticsPlugin]");
            return chain.execute(exchange);
    }

}
